﻿jQuery.extend(jQuery, {
    parseDate: function(value)
    {
        ///<summary>
        ///Parse date, specified in format dd.mm.yyyy [hh:mm] and return date object
        ///</summary>
        var months = [31,28,31,30,31,30,31,31,30,31,30,31];
        if( !/^\d\d?\.\d\d?\.\d\d\d?\d?\s*(\d\d?:\d\d)?$/.test(value) ) return null;
        var dp = value.substr(0,10).split('.');
        var hasTime = (value.length > 10 && value.substr(11).indexOf(':')>0);
        var tp;
        if( hasTime ) tp = value.substr(11).split(':');
        if( !tp || tp.length < 2 ) tp = [0,0];
        
        var h = parseInt(tp[0],10);
        var m = parseInt(tp[1],10);
        
        var dd = parseInt(dp[0],10); 
        var mm = parseInt(dp[1],10) - 1; 
        var yy = parseInt(dp[2],10);

    	if( yy % 4 == 0 ) months[1]++;
        if( dd < 1 || dd > months[mm] || mm < 0 || mm > 11 || yy < 1000 || yy > 9000 || h < 0 || h > 23 || m <0 || m > 59) return null;
        
        //alert( value + ' --> ' + new Date(yy,mm,dd,h,m));
        return new Date(yy,mm,dd,h,m);
    },
    
    getDateString: function(date,hastime)
    {
        var yy = date.getFullYear();
        var mm = $.toTwoDigits(date.getMonth()+1);
        var dd = $.toTwoDigits(date.getDate());

        var str = dd+'.'+mm+'.'+yy;
        if( hastime)
        {        
            var h = $.toTwoDigits(date.getHours());
            var m = $.toTwoDigits(date.getMinutes());
            str = str+' '+h+':'+m;
        }
        //alert( date + ' --> ' + str );
        return str;
    },
    
	toTwoDigits: function(i)
    {
	    if( parseInt(i,10) < 10 ) return '0' + parseInt(i,10).toString();
	    return i;
	}
});